import cv2
import mediapipe
import time

class facedetector():
    def __init__(self,min_detection_confidence=0.6, model_selection=0):
        self.min_confidence = min_detection_confidence
        self.model = model_selection
        self.facedetection = mediapipe.solutions.face_detection.FaceDetection(self.min_confidence,self.model)
        self.Draw = mediapipe.solutions.drawing_utils

    def findFace(self,img,draw=False):

        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        # 打印坐标信息
        self.result = self.facedetection.process(imgRGB)
        bbox_list = []
        if  self.result.detections:
            for id, detection in enumerate(self.result.detections):
                # 打印信息
                # print(x,detection)

                if (draw):
                # 画边框1 自带的api
                    draw.draw_detection(img,detection)

                else:
                    # 画边框2
                    bounding_box = detection.location_data.relative_bounding_box
                    # print(bounding_box)
                    H, W, _ = img.shape
                    x, y, w, h = int(bounding_box.xmin * W), int(bounding_box.ymin * H), int(bounding_box.width * W), int(
                        bounding_box.height * H)
                    cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)

                    cv2.putText(img, f'confidence: {int(detection.score[0] * 100)}%', (x, y), cv2.FONT_HERSHEY_PLAIN, 2,
                                (255, 255, 0), 2)

        return img

def main():
    cap = cv2.VideoCapture(0)
    time1 = time.time()

    face_detect = facedetector(min_detection_confidence=0.7)

    while True:
        success, img = cap.read()

        img = face_detect.findFace(img)

        # 设定帧数
        time2 = time.time()
        fps = 1 / (time2 - time1)
        time1 = time2
        cv2.putText(img, f'FPS:{int(fps)}', (20, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)

        cv2.imshow("output", img)
        if cv2.waitKey(1) & 0xFF == 27:
            break

#当前模块被调用的时候，直接运行  当模块是被导入的时候，代码不运行
if __name__ == '__main__':
    main()